import os
import socket
import subprocess
import time
from starlette.applications import Starlette
from starlette.routing import Mount, Host
from mcp.server import FastMCP

mcp = FastMCP("Demo", port=31099)

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

def find_free_port():
    """自动寻找一个空闲端口"""
    s = socket.socket()
    s.bind(('', 0))
    addr, port = s.getsockname()
    s.close()
    return port

def start_mcp():
    port = find_free_port()
    # 创建子进程运行 MCP 服务
    process = subprocess.Popen(
        ["uvicorn", "mcp_template:mcp", "--host", "0.0.0.0", "--port", str(port)],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        env=os.environ.copy()
    )


    sse_url = f"http://localhost:{port}/sse"
    print(f"✅ MCP started. SSE URL: {sse_url}")
    time.sleep(60)
    return process, sse_url


app = Starlette(
    routes=[
        Mount('/', app=mcp.sse_app()),
    ]
)
if __name__ == "__main__":
    mcp.run(transport='sse')